trigger update_owner_hos on Hospital__c (after update) {

try{

    Boolean change_flag = false;
    List<ID> ID_list = new List<ID>();
    List<Hospital__c> hos1_list = new List<Hospital__c>();
    
    for(Hospital__c hos : trigger.new){
        ID_list.add(hos.Id);
        hos1_list.add(hos);
    }
    for(hospital__C  t:trigger.new){
        if(Trigger.oldmap.get(t.id).OwnerId != t.ownerid)
        {
            change_flag = true;
        }
    }
    
    
    if(change_flag){
    List<HCP__c> hcpl = [Select Id,Name, hcp_owner__c,Hospital__c From HCP__c Where Hospital__c in: ID_list];
    List<Hospital__c> hos1_all = new List<Hospital__c>();
    for(HCP__c hcp1:hcpl)
    {
        for(Hospital__c hos1:hos1_list)
        {
            if(hcp1.Hospital__c == hos1.Id)
            {
                hos1_all.add(hos1);
                break;
            }
        }   
    }
    
    Integer num = 0;
    List<HCP__c> hcp_save = new List<HCP__c>();
    for(HCP__c hcp:hcpl)
    {
        hcp.hcp_owner__c = hos1_all.get(num).OwnerId;
        hcp_save.add(hcp);
        num++;
    }
    update hcp_save;
    }
}
    catch (DmlException e) {
        ApexPages.addMessages(e);

    }
 
}